<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Weather Activity Agent | ZenML</title>

    <!-- ZenML Brand Fonts (Fontsource CDN) -->
    <link
      href="https://cdn.jsdelivr.net/npm/@fontsource-variable/inter@5.0.16/index.min.css"
      rel="stylesheet"
    />
    <link
      href="https://cdn.jsdelivr.net/npm/@fontsource-variable/jetbrains-mono@5.0.16/index.min.css"
      rel="stylesheet"
    />

    <style>
      /* ===== CSS Variables - ZenML Design System ===== */
      :root {
        /* Primary Colors */
        --zenml-purple: #7a3ef4;
        --zenml-purple-dark: #431d93;
        --zenml-purple-light: #e4d8fd;
        --zenml-purple-lighter: #f1ebfe;
        --zenml-purple-mid: #9565f6;

        /* Neutral Colors */
        --text-primary: #0d061d;
        --text-secondary: #6b7280;
        --text-tertiary: #9ca3af;
        --surface-primary: #ffffff;
        --surface-secondary: #f9fafb;
        --surface-tertiary: #f3f4f6;

        /* Semantic Colors */
        --success: #1cbf4a;
        --success-light: #d2f2db;
        --warning: #f98b0a;
        --warning-light: #fff6ea;
        --error: #eb483d;
        --error-light: #fbdad8;

        /* Border Colors */
        --border-moderate: #e5e7eb;
        --border-bold: #6b7280;

        /* Typography */
        --font-ui: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI",
          Roboto, sans-serif;
        --font-mono: "JetBrains Mono", "SF Mono", Monaco, "Courier New",
          monospace;

        /* Spacing Scale (8pt grid) - Default: spacing/4 = 24px */
        --spacing-xs: 4px;
        --spacing-sm: 8px;
        --spacing-md: 16px;
        --spacing-lg: 24px;
        --spacing-xl: 32px;
        --spacing-2xl: 48px;

        /* Shadows */
        --shadow-subtle: 0 1px 3px rgba(0, 0, 0, 0.1);
        --shadow-standard: 0 2px 8px rgba(0, 0, 0, 0.1);
        --shadow-emphasized: 0 4px 16px rgba(0, 0, 0, 0.15);

        /* Border Radius */
        --radius-sm: 4px;
        --radius-md: 8px;
        --radius-lg: 12px;
        --radius-full: 999px;
      }

      /* ===== Reset & Base Styles ===== */
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: var(--font-ui);
        background: var(--surface-secondary);
        color: var(--text-primary);
        padding: var(--spacing-xl);
        font-size: 16px;
        line-height: 24px;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
      }

      /* ===== Layout ===== */
      .container {
        max-width: 800px;
        margin: 0 auto;
      }

      .card {
        background: var(--surface-primary);
        border: 1px solid var(--border-moderate);
        border-radius: var(--radius-md);
        padding: var(--spacing-lg);
        box-shadow: var(--shadow-standard);
      }

      /* ===== Hero Section ===== */
      .hero {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: var(--spacing-lg);
        margin-bottom: var(--spacing-lg);
        padding-bottom: var(--spacing-lg);
        border-bottom: 1px solid var(--border-moderate);
      }

      .hero-copy {
        flex: 1;
      }

      .title {
        margin: 0 0 var(--spacing-sm) 0;
        font-size: 28px;
        font-weight: 600;
        line-height: 36px;
        color: var(--text-primary);
      }

      .subtitle {
        margin: 0;
        font-size: 16px;
        line-height: 24px;
        color: var(--text-secondary);
      }

      .hero-art svg {
        display: block;
        filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.08));
      }

      /* ===== Section ===== */
      .section {
        margin-top: var(--spacing-lg);
      }

      .section h2 {
        font-size: 20px;
        font-weight: 600;
        line-height: 28px;
        color: var(--text-primary);
        margin-bottom: var(--spacing-md);
      }

      /* ===== Form ===== */
      .form-row {
        display: flex;
        gap: var(--spacing-sm);
        align-items: center;
        flex-wrap: wrap;
      }

      .input {
        flex: 1;
        min-width: 200px;
        padding: 12px 16px;
        border: 1px solid var(--border-moderate);
        border-radius: var(--radius-md);
        font-family: var(--font-ui);
        font-size: 16px;
        line-height: 24px;
        color: var(--text-primary);
        background: var(--surface-primary);
        transition: border-color 0.2s ease, box-shadow 0.2s ease;
      }

      .input::placeholder {
        color: var(--text-tertiary);
      }

      .input:focus {
        outline: none;
        border-color: var(--zenml-purple);
        box-shadow: 0 0 0 3px rgba(122, 62, 244, 0.1);
      }

      /* ===== Buttons ===== */
      .btn {
        padding: 12px 24px;
        border: none;
        border-radius: var(--radius-md);
        font-family: var(--font-ui);
        font-size: 14px;
        font-weight: 600;
        line-height: 20px;
        cursor: pointer;
        transition: background-color 0.2s ease, transform 0.1s ease,
          box-shadow 0.2s ease;
      }

      .btn:disabled {
        opacity: 0.4;
        cursor: not-allowed;
      }

      .btn:active:not(:disabled) {
        transform: translateY(1px);
      }

      /* Primary Button */
      .btn:not(.secondary) {
        background: var(--zenml-purple);
        color: var(--surface-primary);
      }

      .btn:not(.secondary):hover:not(:disabled) {
        background: var(--zenml-purple-dark);
        box-shadow: var(--shadow-standard);
      }

      /* Secondary Button */
      .btn.secondary {
        background: var(--surface-primary);
        color: var(--zenml-purple);
        border: 1px solid var(--border-moderate);
      }

      .btn.secondary:hover:not(:disabled) {
        background: var(--surface-tertiary);
      }

      /* ===== Status Pill ===== */
      .status-pill {
        display: inline-block;
        padding: 6px 12px;
        border-radius: var(--radius-full);
        font-size: 12px;
        font-weight: 600;
        line-height: 18px;
        margin-top: var(--spacing-sm);
      }

      .status-pill.auth-set {
        background: var(--success-light);
        color: var(--success);
      }

      .status-pill.auth-required {
        background: var(--warning-light);
        color: var(--warning);
      }

      /* ===== Messages ===== */
      .message {
        margin-top: var(--spacing-md);
        padding: var(--spacing-md);
        border-radius: var(--radius-md);
        font-size: 14px;
        line-height: 20px;
      }

      .message.info {
        background: var(--zenml-purple-lighter);
        color: var(--zenml-purple);
        border: 1px solid var(--zenml-purple-light);
      }

      .message.error {
        background: var(--error-light);
        color: var(--error);
        border: 1px solid var(--error);
      }

      /* ===== Result Display ===== */
      .result {
        margin-top: var(--spacing-lg);
        padding: var(--spacing-lg);
        border: 1px solid var(--border-moderate);
        border-radius: var(--radius-md);
        background: var(--surface-secondary);
        white-space: pre-wrap;
      }

      .result:empty {
        display: none;
      }

      /* Markdown content styling */
      .result h1,
      .result h2,
      .result h3 {
        color: var(--text-primary);
        margin: var(--spacing-md) 0 var(--spacing-sm);
        font-weight: 600;
      }

      .result h1 {
        font-size: 24px;
        line-height: 32px;
      }

      .result h2 {
        font-size: 20px;
        line-height: 28px;
      }

      .result h3 {
        font-size: 16px;
        line-height: 24px;
      }

      .result p {
        margin: var(--spacing-sm) 0;
        line-height: 1.6;
        color: var(--text-primary);
      }

      .result ul {
        padding-left: 20px;
        margin: var(--spacing-sm) 0;
      }

      .result li {
        margin: var(--spacing-xs) 0;
        color: var(--text-primary);
      }

      .result code {
        background: var(--surface-tertiary);
        padding: 2px 6px;
        border-radius: var(--radius-sm);
        font-family: var(--font-mono);
        font-size: 13px;
        color: var(--zenml-purple);
      }

      /* ===== Metrics Grid ===== */
      .metrics {
        margin-top: var(--spacing-lg);
      }

      .metrics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: var(--spacing-md);
      }

      .metric-card {
        display: flex;
        align-items: center;
        gap: var(--spacing-md);
        padding: var(--spacing-md);
        border-radius: var(--radius-md);
        background: var(--surface-primary);
        border: 1px solid var(--border-moderate);
        box-shadow: var(--shadow-subtle);
        transition: box-shadow 0.2s ease;
      }

      .metric-icon {
        width: 40px;
        height: 40px;
        flex-shrink: 0;
      }

      .metric-content {
        display: flex;
        flex-direction: column;
        gap: var(--spacing-xs);
        flex: 1;
      }

      .metric-label {
        color: var(--text-secondary);
        font-size: 12px;
        font-weight: 600;
        line-height: 18px;
        text-transform: uppercase;
        letter-spacing: 0.02em;
      }

      .metric-value {
        font-weight: 600;
        font-size: 20px;
        line-height: 28px;
        color: var(--text-primary);
      }

      .metric-note {
        font-size: 12px;
        line-height: 18px;
        color: var(--text-secondary);
      }

      /* Severity color coding */
      .sev-good {
        border-color: var(--success);
        background: var(--success-light);
      }

      .sev-info {
        border-color: var(--zenml-purple-light);
        background: var(--zenml-purple-lighter);
      }

      .sev-warn {
        border-color: var(--warning);
        background: var(--warning-light);
      }

      .sev-bad {
        border-color: var(--error);
        background: var(--error-light);
      }

      /* ===== Footer ===== */
      .footer {
        text-align: center;
        padding: var(--spacing-lg);
        background: var(--surface-secondary);
        color: var(--text-secondary);
        font-size: 14px;
        line-height: 20px;
        border-top: 1px solid var(--border-moderate);
        margin: var(--spacing-lg) calc(var(--spacing-lg) * -1)
          calc(var(--spacing-lg) * -1);
        border-radius: 0 0 var(--radius-md) var(--radius-md);
      }

      .footer strong {
        color: var(--zenml-purple);
        font-weight: 600;
      }

      /* ===== Responsive Design ===== */
      @media (max-width: 768px) {
        body {
          padding: var(--spacing-md);
        }

        .hero {
          flex-direction: column;
          align-items: flex-start;
        }

        .hero-art {
          width: 100%;
          display: flex;
          justify-content: center;
        }

        .form-row {
          flex-direction: column;
          align-items: stretch;
        }

        .input {
          min-width: 100%;
        }

        .btn {
          width: 100%;
        }

        .metrics-grid {
          grid-template-columns: 1fr;
        }
      }
    </style>
  </head>
  <body>

    <div class="container">
      <div class="card">
        <!-- Hero Section -->
        <div class="hero">
          <div class="hero-copy">
            <h1 class="title">Weather Activity Agent</h1>
            <p class="subtitle">
              Type a city and get curated, weather-aware activity ideas.
            </p>
          </div>
          <div class="hero-art" aria-hidden="true">
            <!-- Weather illustration with ZenML purple -->
            <svg
              width="140"
              height="100"
              viewBox="0 0 140 100"
              xmlns="http://www.w3.org/2000/svg"
            >
              <defs>
                <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stop-color="#cab2fb" />
                  <stop offset="100%" stop-color="#f1ebfe" />
                </linearGradient>
              </defs>
              <rect
                x="0"
                y="0"
                width="140"
                height="100"
                rx="12"
                fill="url(#sky)"
              />
              <!-- Sun -->
              <circle cx="30" cy="30" r="16" fill="#f98b0a" />
              <!-- Cloud -->
              <g fill="#e5e7eb">
                <ellipse cx="95" cy="40" rx="26" ry="14" />
                <ellipse cx="78" cy="44" rx="18" ry="12" />
                <ellipse cx="112" cy="44" rx="18" ry="12" />
              </g>
              <!-- Raindrops with ZenML purple -->
              <g fill="#7a3ef4">
                <path d="M78 60 l3 8 l-6 0 z" />
                <path d="M95 60 l3 8 l-6 0 z" />
                <path d="M112 60 l3 8 l-6 0 z" />
              </g>
            </svg>
          </div>
        </div>

        <!-- Form Section -->
        <div class="section">
          <h2>Try it</h2>
          <div class="form-row">
            <input
              id="city-input"
              class="input"
              type="text"
              list="city-suggestions"
              placeholder="Enter city name"
            />
            <datalist id="city-suggestions">
              <option value="San Francisco"></option>
              <option value="London"></option>
              <option value="Berlin"></option>
              <option value="New York"></option>
              <option value="Tokyo"></option>
            </datalist>
            <button id="fetch-btn" class="btn">Get Suggestions</button>
            <button
              id="set-key-btn"
              class="btn secondary"
              style="display: none"
            >
              Set API Key
            </button>
          </div>
          <div
            id="auth-status"
            class="status-pill auth-required"
            style="display: none"
          >
            Auth required
          </div>
          <div id="message" class="message"></div>

          <!-- Metrics Display -->
          <div id="metrics" class="metrics"></div>

          <!-- Result Display -->
          <div id="result" class="result"></div>
        </div>

        <!-- Footer -->
        <div class="footer">
          Powered by <strong>ZenML</strong> Pipeline Deployments | Real-time
          inference
        </div>
      </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.1.7/dist/purify.min.js"></script>
<script>
    if (typeof marked !== 'undefined' && typeof marked.setOptions === 'function') {
        marked.setOptions({ gfm: true, breaks: true });
    }
    const INVOKE_URL = "{{ service_info.app.invoke_url_path }}";
    const AUTH_ENABLED = {{ 'true' if service_info.deployment.auth_enabled else 'false' }};
    const cityInput = document.getElementById('city-input');
    const fetchBtn = document.getElementById('fetch-btn');
    const messageEl = document.getElementById('message');
    const metricsEl = document.getElementById('metrics');
    const setKeyBtn = document.getElementById('set-key-btn');
    const authStatus = document.getElementById('auth-status');
    const API_KEY_STORAGE = 'weather_agent_api_key';
    const resultEl = document.getElementById('result');

    function setLoading(isLoading) {
        fetchBtn.disabled = isLoading;
        fetchBtn.textContent = isLoading ? 'Fetching...' : 'Get Suggestions';
        if (isLoading) {
            messageEl.textContent = 'Fetching suggestions...';
            messageEl.className = 'message info';
        }
    }

    function showError(text) {
        messageEl.textContent = text;
        messageEl.className = 'message error';
    }

    function clearMessage() {
        messageEl.textContent = '';
        messageEl.className = 'message';
    }

    initAuthUI();

    async function fetchSuggestions() {
        const city = cityInput.value.trim();
        if (!city) {
            showError('Please enter a city name.');
            return;
        }
        if (AUTH_ENABLED && !getApiKey()) {
            await promptForApiKey();
            if (!getApiKey()) {
                showError('API key is required to call the service.');
                return;
            }
        }
        setLoading(true);
        resultEl.innerHTML = '';
        metricsEl.innerHTML = '';
        try {
            const headers = { 'Content-Type': 'application/json' };
            const key = getApiKey();
            if (AUTH_ENABLED && key) headers['Authorization'] = `Bearer ${key}`;
            const res = await fetch(INVOKE_URL, {
                method: 'POST',
                headers,
                body: JSON.stringify({ parameters: { city: city } })
            });
            if (!res.ok) {
                const text = await res.text();
                throw new Error('Request failed: ' + res.status + ' ' + text);
            }
            const data = await res.json();
            if (!data.success) {
                const err = data.error || 'Unknown error from service.';
                throw new Error(err);
            }
            const outputs = data.outputs || {};
            const weather = outputs.weather_data || null;
            const md = outputs.weather_analysis;
            if (!md) {
                messageEl.textContent = 'No analysis returned.';
                messageEl.className = 'message info';
                return;
            }
            if (weather) {
                renderMetrics(weather);
            }
            const html = marked.parse(md);
            resultEl.innerHTML = DOMPurify.sanitize(html);
            clearMessage();
        } catch (e) {
            showError(e.message || String(e));
        } finally {
            setLoading(false);
        }
    }

    fetchBtn.addEventListener('click', fetchSuggestions);
    cityInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') { fetchSuggestions(); }
    });

    function initAuthUI() {
        if (!AUTH_ENABLED) return;
        setKeyBtn.style.display = '';
        authStatus.style.display = '';
        updateAuthStatus();
        setKeyBtn.addEventListener('click', promptForApiKey);
    }

    async function promptForApiKey() {
        const current = getApiKey() || '';
        const entered = prompt('Enter API Key (Bearer token):', current ? '********' : '');
        if (entered === null) return; // canceled
        if (entered === '********') return; // keep existing
        const trimmed = (entered || '').trim();
        if (!trimmed) {
            localStorage.removeItem(API_KEY_STORAGE);
        } else {
            localStorage.setItem(API_KEY_STORAGE, trimmed);
        }
        updateAuthStatus();
    }

    function getApiKey() { return localStorage.getItem(API_KEY_STORAGE); }

    function updateAuthStatus() {
        const hasKey = !!getApiKey();
        authStatus.textContent = hasKey ? 'API key set' : 'Auth required';
        authStatus.style.background = hasKey ? '#ecfdf5' : '#eef2ff';
        authStatus.style.color = hasKey ? '#065f46' : '#3730a3';
        setKeyBtn.textContent = hasKey ? 'Update API Key' : 'Set API Key';
    }

    function renderMetrics(weather) {
        const tiles = [];
        tiles.push(renderMetricTile('Temperature', `${formatTemp(weather.temperature)}`,
            tempIcon(), tempSeverity(weather.temperature), tempNote(weather.temperature)));
        tiles.push(renderMetricTile('Humidity', `${formatPercent(weather.humidity)}`,
            humidityIcon(), humiditySeverity(weather.humidity), humidityNote(weather.humidity)));
        tiles.push(renderMetricTile('Wind Speed', `${formatWind(weather.wind_speed)}`,
            windIcon(), windSeverity(weather.wind_speed), windNote(weather.wind_speed)));
        metricsEl.innerHTML = `
            <div class="metrics-grid">
                ${tiles.join('')}
            </div>
        `;
    }

    function renderMetricTile(label, value, iconSvg, sevClass, note) {
        const classes = `metric-card ${sevClass}`;
        return `
            <div class="${classes}">
                <div class="metric-icon">${iconSvg}</div>
                <div class="metric-content">
                    <div class="metric-label">${label}</div>
                    <div class="metric-value">${value}</div>
                    ${note ? `<div class="metric-note">${note}</div>` : ''}
                </div>
            </div>
        `;
    }

    // Formatters
    function formatTemp(t) { return `${t.toFixed(1)}°C`; }
    function formatPercent(p) { return `${Number(p).toFixed(0)}%`; }
    function formatWind(w) { return `${Number(w).toFixed(0)} km/h`; }

    // Severity helpers
    function tempSeverity(t) {
        if (t < 0) return 'sev-bad';
        if (t < 10) return 'sev-warn';
        if (t <= 25) return 'sev-good';
        if (t <= 32) return 'sev-warn';
        return 'sev-bad';
    }
    function humiditySeverity(h) {
        if (h < 20) return 'sev-warn';
        if (h <= 60) return 'sev-good';
        if (h <= 80) return 'sev-warn';
        return 'sev-bad';
    }
    function windSeverity(w) {
        if (w < 10) return 'sev-good';
        if (w <= 20) return 'sev-info';
        if (w <= 35) return 'sev-warn';
        return 'sev-bad';
    }

    // Notes
    function tempNote(t) {
        if (t < 0) return 'Freezing. Dress in heavy layers.';
        if (t < 10) return 'Chilly. Bring a jacket.';
        if (t <= 25) return 'Comfortable range for most.';
        if (t <= 32) return 'Warm. Hydrate and seek shade.';
        return 'Hot. Limit strenuous activity.';
    }
    function humidityNote(h) {
        if (h < 20) return 'Dry air; consider moisturizing.';
        if (h <= 60) return 'Comfortable humidity.';
        if (h <= 80) return 'Humid; may feel muggy.';
        return 'Very humid; watch for discomfort.';
    }
    function windNote(w) {
        if (w < 10) return 'Calm to gentle breeze.';
        if (w <= 20) return 'Breezy; hold onto hats.';
        if (w <= 35) return 'Windy; secure loose items.';
        return 'Strong winds; take caution.';
    }

    // Icons (inline SVG)
    function tempIcon() {
        return `
        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M10 14.5a4.5 4.5 0 1 0 4 0V5a2 2 0 1 0-4 0v9.5z" stroke="#ef4444" stroke-width="1.5"/>
          <path d="M10 10h4" stroke="#ef4444" stroke-width="1.5"/>
          <circle cx="12" cy="18" r="3" fill="#fecaca" />
        </svg>`;
    }
    function humidityIcon() {
        return `
        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 3s5 5.2 5 9a5 5 0 0 1-10 0c0-3.8 5-9 5-9z" fill="#bfdbfe" stroke="#3b82f6" stroke-width="1.5"/>
        </svg>`;
    }
    function windIcon() {
        return `
        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M3 8h10a3 3 0 1 0-3-3" stroke="#60a5fa" stroke-width="1.5" stroke-linecap="round"/>
          <path d="M3 12h14a3 3 0 1 1-3 3" stroke="#60a5fa" stroke-width="1.5" stroke-linecap="round"/>
        </svg>`;
    }
</script>